<template>
  <el-dialog
    v-model="dialogVisible"
    title="新 增"
    width="500"
    overflow
    @close="handleClose"
  >
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item
        label="姓名"
        :label-width="formLabelWidth"
        style="width: 90%"
        prop="Name"
      >
        <el-input
          v-model="form.Name"
          autocomplete="off"
          placeholder="请输入 姓名"
        />
      </el-form-item>
      <el-form-item
        label="手机号"
        :label-width="formLabelWidth"
        style="width: 90%"
        prop="Phone"
      >
        <el-input
          v-model="form.Phone"
          autocomplete="off"
          placeholder="请输入 手机号"
          @blur="validatePhone"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" color="#1E3485" @click="go(ruleFormRef)">
          保存
        </el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch, onMounted } from "vue";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";

import { ElMessage, ElMessageBox } from "element-plus";
const ruleFormRef = ref<FormInstance>();
const emit = defineEmits(["close", "confirm"]);
function handleClose() {
  emit("close", false);
}

// 弹窗关闭/打开事件
const props = defineProps({
  visible: Boolean
});

const rules = reactive({
  Name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  Phone: [{ required: true, message: "请输入手机号", trigger: "blur" }]
});

const dialogVisible = ref(false);
const formLabelWidth = "80px";

watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  },
  { immediate: true }
);
const form = reactive({
  Name: "",
  Phone: ""
});

const go = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      emit("close", form);
      dialogVisible.value = false;
      form.Name = "";
      form.Phone = "";
    } else {
      console.log("error submit!", fields);
    }
  });
};

function validateName(value) {
  // const phoneRegex = /^[\u4e00-\u9fa5]{2,4}$/;
  // if (!phoneRegex.test(form.Name)) {
  //   // 这里可以添加不匹配时的处理逻辑，例如提示用户
  //   ElMessage.error("请输入正确的姓名");
  //   form.Name = "";
  // }
}
function validatePhone(value) {
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(form.Phone)) {
    // 这里可以添加不匹配时的处理逻辑，例如提示用户
    ElMessage.error("请输入有效的手机号码");
    form.Phone = "";
  }
}
</script>
